package com.xzz.tree;

/**
 * @author: hhz
 * @create: 2021-12-20 14:14
 * 230 二叉搜索树中第K小的元素
 **/
public class KthSmallest {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(3);
        TreeNode node2 = new TreeNode(1);
        TreeNode node3 = new TreeNode(4);
        TreeNode node4 = new TreeNode(2);
        node1.left = node2;
        node1.right = node3;
        node2.right = node4;
        System.out.println(kthSmallest(node1, 1));
    }
    static int index = 0;
    static int result = 0;

    public static int kthSmallest(TreeNode root, int k) {
        index = 0;
        result = 0;
        find(root, k);
        return result;
    }

    public static void find(TreeNode root, int k) {
        if (root == null) {
            return;
        }
        find(root.left, k);

        index++;
        if (index == k) {
            result = root.val;
            return;
        }
        find(root.right, k);
    }
}
